package com.netty.chat.server;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by haoxy on 2019/1/4.
 * E-mail:hxyHelloWorld@163.com
 * github:https://github.com/haoxiaoyong1014
 * 通道初始化器
 * 用来加载通道处理器
 */
@Component
@ChannelHandler.Sharable
public class WsServerInitializer extends ChannelInitializer<SocketChannel> {
    @Autowired
    ChatHandler chatHandler;
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //用于支持 http协议
        //websocket握手阶段基于http协议,需要 http的编码器
        pipeline.addLast(new HttpServerCodec())
                //对大数据流的支持
                .addLast(new ChunkedWriteHandler())
                //添加对HTTP请求和响应的聚合器: 只要Netty进行编码都需要使用
                //对HttpMessage进行聚合,聚合成FullHttpRequest获取FullHttpResponse
                .addLast(new HttpObjectAggregator(1024 * 64))
                /**
                 * 使用websocket的协议解决http协议的一大难题：服务器只能被动接收客服端的消息并回复，而无法主动发送消息
                 * websocket协议实现实时双端通信，而不必采用轮询等机制去获取服务器的消息
                 * 彻底摆脱http协议的 request-response的限制
                 */
                .addLast(new WebSocketServerProtocolHandler("/ws"))
                //添加自定义的 handler
                .addLast(chatHandler);
    }
}
